package com.bootdo.common.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.bootdo.common.config.Constant;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/***
 * 发送短信
 */
@Slf4j
public class SendUtils {

    /***
     * 阿里云短信发送
     * @param phone
     * @param code
     * @return
     * @throws ClientException
     */
    public static R sendSms(String phone, String code) {

        //可自助调整超时时间
        DefaultProfile profile = DefaultProfile.getProfile("default", Constant.ACCESS_KEY_ID, Constant.ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        //封装请求对象
        CommonRequest request = new CommonRequest();
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setAction("SendSms");
        request.setVersion("2017-05-25");
        request.setMethod(MethodType.POST);
        //确定发送的电话号码和 验证码
        request.putQueryParameter("PhoneNumbers", phone);
        //这里也得注意，对应的值是Json格式的字符串，不然就是一杯茶一根烟，一个bug玩一天
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        //确定是的模版和签名
        request.putQueryParameter("SignName", Constant.SIGN_NAME);
        request.putQueryParameter("TemplateCode", Constant.VERIFY_CODE_TEMPLATE);
        //发起调用
        try {
            CommonResponse response = client.getCommonResponse(request);
            if (response != null && response.getHttpStatus() == 200){
                String data = response.getData();
                Map map = JSON.parseObject(data, Map.class);
                log.info("短信发送状态:{}" + phone + "=====" + code + "=====" + map.get("Message"));
                if(null == map) {
                    return R.error("短信发送失败");
                }
                if(!StringUtils.equals((CharSequence) map.get("Code"),"OK")) {
                    return R.error("短信发送失败");
                }
            }else {
                return R.error("短信发送失败");
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

}
